<?php

namespace App\Dao\Users;

use App\Model\User\User;
use Yj\Daos\BaseDaos;
use App\Model\Users\Users;
use Hyperf\Database\Model\Builder;
use Yj\Daos\Verify;
use Hyperf\Utils\Collection;

/**
 * @var Users
 * @method $this params($params)
 */
class UsersDao extends BaseDaos
{
    const MODEL = User::class;

    public function searchParams(Collection $params)
    {
        $search = $this->getSearch();
        $params->check('id', function ($id) use ($search) {
            $search->where('id', $id);
        });
        $params->check('uid', function ($id) use ($search) {
            $search->where('uid', $id);
        });

        $params->check('phone', function ($phone) use ($search) {
            $search->where('phone', 'like', '%' . $phone . '%');
        });
        $params->check('nickname', function ($nickname) use ($search) {
            $search->where('nickname', 'like', '%' . $nickname . '%');
        });
        $params->check('user_type', function ($user_type) use ($search) {
            $search->where('user_type', $user_type);
        });

        return $search;
    }

    public function lists(Collection $params)
    {
        $data = $this->params($params)->orderByDesc("uid")->getList();
        return $data;
    }

    public function add(Collection $params)
    {
        $data = $this->create($params->toArray());
        return $data;
    }

    public function edit(int $id, Collection $params)
    {
        $data = $this->params(_Collect(["id" => $id]))->firstOrError();
        $data->fill($params->toArray());
        return $data->save();
    }

    public function read(int $id)
    {
        $data = $this->params(_Collect(["uid" => $id]))->firstOrError();
        return $data;
    }

    public function del(int $id)
    {
        $data = $this->params(_Collect(["id" => $id]))->firstOrError();
        return $data->delete();
    }

    public function getSpreadPeople($uid)
    {
        return $this->where('spread_uid', $uid)->where('is_spread', 1)->count();
    }
}
